import random
import time

import pandas as pd
import pyautogui
import pyperclip
from pynput.keyboard import Key, Controller
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

from lib.chrome import BrowserDev
from utils.seleniumUtils import presence_of_element_located

browserDev = BrowserDev()  # 浏览器对象，工厂
driver = browserDev.init()
keyboard = Controller()
driver.implicitly_wait(10)


# driver = webdriver.Chrome()

def read_rewrite():
    # 读取/data/rewrite.txt文件
    with open("./data/rewrite.txt", "r") as f:
        return f.read()


class ChatGPT:
    def __init__(self):
        self.driver = driver
        self.rewrite_prompt = read_rewrite()

    def run(self, topic):
        """
        运行
        :param topic:
        :return:
        """

        self.driver.get("https://chatgpt.com/")

        self.fill_content(f'Write SEO optimized Blog Post on Topic "{topic}"')  # 填写内容
        time.sleep(random.randint(3, 5))
        self.driver.find_element(By.CLASS_NAME, "icon-2xl").click()
        self.wait_loading()  # 等待加载
        time.sleep(random.randint(3, 5))
        self.fill_content(self.rewrite_prompt)  # 填写内容, 重写
        time.sleep(random.randint(3, 5))
        self.driver.find_element(By.CLASS_NAME, "icon-2xl").click()

        self.wait_loading()  # 等待加载

        var = self.driver.find_elements(By.XPATH,
                                        '//div[contains(@class, "w-full") and contains(@class, "text-token-text-primary")]')[
            -1].find_elements(By.XPATH,
                              "//div[@class='items-center justify-start rounded-xl p-1 flex']/div/span/button")[1]
        var.click()
        return pyperclip.paste()

    def wait_loading(self):
        """
        等待回复完毕
        """
        flag = False

        while True:
            if not presence_of_element_located(self.driver, By.CLASS_NAME, "icon-2xl"): flag = True
            if flag and presence_of_element_located(self.driver, By.CLASS_NAME, "icon-2xl"): break
            if presence_of_element_located(self.driver, By.XPATH, '//button[@class="btn relative btn-primary m-auto"]'):
                raise Exception("重新生成按钮出现，需要重新生成")
                # 如果出现重新生成按钮，则点击
                # self.driver.find_element(By.XPATH, '//button[@class="btn relative btn-primary m-auto"]').click()

    def fill_content(self, content):
        """
        填写内容
        :param content:
        :return:
        """
        pyperclip.copy(content)  # 将内容复制到剪贴板
        input_ele = self.driver.find_element(By.ID, "prompt-textarea")
        input_ele.send_keys(Keys.CONTROL, 'v')  # 粘贴内容


def switch_to_new_tab(driver):
    with keyboard.pressed(Key.ctrl):
        keyboard.press('t')
        keyboard.release('t')
        # 使用 keyboard.write 方法快速输入
    pyautogui.write("https://chatgpt.com/")
    # 模拟回车键chatgpt.com
    pyautogui.press('enter')
    pyautogui.press('enter')
    # 等待2秒，以便切换到目标窗口
    time.sleep(random.randint(8, 10))
    # 按 Tab 键
    pyautogui.press('tab')

    # 按 Space 键
    pyautogui.press('space')
    # 获取所有窗口句柄
    all_windows = driver.window_handles

    # 切换到最后一个窗口
    driver.switch_to.window(all_windows[-1])


if __name__ == '__main__':
    try:
        # 读取csv文件
        df = pd.read_csv("./data/topiclist_holidayserenity_Accommodation.csv")
        chatgpt = ChatGPT()
        # 遍历每一行
        for index, row in df.iterrows():
            if row['state'] == 1: continue  # 如果state为1则跳过
            reply = ''
            while True:
                try:
                    reply = chatgpt.run(row['topiclist'])
                except Exception as e:

                    print("出现验证，开始解决验证问题", e)
                    browserDev.close()
                    driver.quit()
                    browserDev = BrowserDev()  # 浏览器对象，工厂
                    driver = browserDev.init()
                    chatgpt = ChatGPT()
                    if type(e) == NoSuchElementException:
                        switch_to_new_tab(driver)
                        print("通过验证")
                    continue
                break
            # 将生成的回复添加到reply列
            df.loc[index, 'reply'] = reply
            # 将state置为1
            df.loc[index, 'state'] = 1
            # 保存修改后的dataframe
            df.to_csv("./data/topiclist_holidayserenity_Accommodation.csv", index=False)
    except Exception as e:
        print(e, "未知异常捕获")
